import { getInfo, getLogin } from '@/api/login'
import { routerArrays } from '@/layout/types'
import { resetRouter, router } from '@/router'
import { store } from '@/store'
import { removeToken, setToken } from '@/utils/auth'
import { isEmpty } from 'lodash-es'
import { defineStore } from 'pinia'
import { useMultiTabStore } from './multiTab'
import type { userType } from './types'

export const useUserStore = defineStore({
  id: 'pure-user',
  state: () =>
    ({
      isAdmin: false,
      // 用户名
      username: '',
      // 账号名
      userAccountName: '',
      // 页面级别权限
      roles: [],
      permissions: [],
      avatar: '',
      userId: '',
    }) as userType,
  getters: {
    isAuthenticated: (state) => !isEmpty(state.username),
  },
  actions: {
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username
    },
    SET_USERACCOUNTNAME(userAccountName: string) {
      this.userAccountName = userAccountName
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles
    },
    /** 登入 */
    async loginByUsername(data) {
      const res = await getLogin(data)
      if (res.data) {
        setToken(res.data.access_token)
      }
      return res.data
    },
    // 获取用户信息
    async getInfo() {
      const res = await getInfo()
      const { data } = res
      const { user } = data

      if (data.roles && data.roles.length > 0) {
        // 验证返回的roles是否是一个非空数组
        this.roles = data.roles
        this.permissions = data.permissions
      } else {
        this.roles = ['ROLE_DEFAULT']
      }

      // this.name = user.userName;
      this.userAccountName = user.userName
      this.username = user.nickName
      this.avatar = user.avatar
      this.userId = user.userId
      this.isAdmin = this.roles.includes('admin')
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = ''
      this.roles = []
      removeToken()
      useMultiTabStore().setTabs([...routerArrays])
      resetRouter()
      router.push('/login')
    },
  },
})

export function useUserStoreHook() {
  return useUserStore(store)
}
